package com.gagakuai.bpm.config.redis;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;

/*
 * 序列化
 */
public class ObjectSerializer<V> implements RedisSerializer<V> {

    private final Converter<Object, byte[]> serializer = new SerializingConverter();
    private final Converter<byte[], Object> deserializer = new DeserializingConverter();
    private static final byte[] EMPTY_ARRAY = new byte[0];

    @SuppressWarnings("unchecked")
    @Override
    public V deserialize(byte[] bytes) {
        if (isEmpty(bytes)) {
            return null;
        }
        try {
            return (V) deserializer.convert(bytes);
        } catch (Exception ex) {
            ex.printStackTrace(System.err);
            return null;
        }
    }

    @Override
    public byte[] serialize(V object) {
        try {
            return serializer.convert(object);
        } catch (Exception ex) {
            ex.printStackTrace(System.err);
            return EMPTY_ARRAY;
        }
    }

    private boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }
}